<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;


class UserController extends Controller{
    public function __construct() {
        $this->middleware('auth')->except(['create','show','store','index','confirmEmail']);
        $this->middleware('guest')->only(['create']);
        $this->middleware('throttle:10,1', [
            'only' => ['store']
        ]);
    }

    public function index(){
        $users = User::paginate(8);
        return view('user.list',compact('users'));
    }
    public function create(){
        return view('user.create');
    }
    public function show(User $user){
        $topics = $user->topics()->orderBy('created_at','desc')->paginate(10);
        return view('user.show',compact('user','topics'));
    }
    public function store(Request $request){
       $this->validate($request,[
           'name'=>'required|unique:users|max:50',
           'email'=>['required','email',Rule::unique('users')],
           'password'=>['required','confirmed','min:6']
       ]);

      $user =  User::create([
           'name'=>$request->input('name'),
           'email'=>$request->email,
           'avatar'=>'/faker/images/avatars/avatar'.rand(1,7).'.png',
           'password'=>Hash::make($request->password)
       ]);
        $this->sendEmailConfirmationTo($user);
        session()->flash('success', '验证邮件已发送到你的注册邮箱上，请注意查收并激活。');
        return redirect('/');
//       Auth::login($user);
//       session()->flash('success','恭喜您，注册账号成功，祝您学有所成！');
//       return redirect()->route('user.show',[$user]);
    }
    public function edit(User $user){
        $this->authorize('update', $user);
        return view('user.edit',compact('user'));
    }
    public function update(Request $request,User $user){
        $this->authorize('update', $user);
        $this->validate($request,[
            'name'=>['required',Rule::unique('users','name')->ignore(request('user.id')),'max:50'],
            'password'=>['nullable','confirmed','min:6']
        ]);

        $data = [];
        $data['name'] = $request->name;
        if($request->password){
            $data['password'] = bcrypt($request->password);
        }
        $user->update($data);
        session()->flash('success','恭喜您，修改账号信息成功！');
        return redirect()->route('user.show',$user);
    }
    public function destroy(User $user){
        $this->authorize('destroy', $user);
        $user->delete();
        session()->flash('success', '成功删除用户！');
        return back();
    }

    protected function sendEmailConfirmationTo($user){
        $view = 'emails.confirm';
        $data = compact('user');
        $to = $user->email;
        $subject = "感谢注册TopWeibo！请确认你的邮箱。";
        Mail::send($view, $data, function ($message) use ($to, $subject) {
            $message->to($to)->subject($subject);
            //$message->from($from, $name)->to($to)->subject($subject);
        });
    }
    public function confirmEmail($token){
        $user = User::where('activation_token', $token)->firstOrFail();
        $user->activated = true;
        $user->activation_token = null;
        $user->save();
        Auth::login($user);
        session()->flash('success', '恭喜你，账号激活成功！');
        return redirect()->route('user.show', [$user]);
    }
    public function followings(User $user){
        $users = $user->followings()->paginate(5);
        $title = $user->name . '关注的人';
        return view('user.show_follow', compact('users', 'title'));
    }

    public function followers(User $user)
    {
        $users = $user->followers()->paginate(5);
        $title = $user->name . '的粉丝';
        return view('user.show_follow', compact('users', 'title'));
    }


}
